package smashedapples.air.sqlite.commands
{
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	
	import smashedapples.air.sqlite.SQLiteDB;
	import smashedapples.air.sqlite.events.SQLiteSaveEvent;
	import smashedapples.air.sqlite.responses.SQLiteSaveResponse;
	
	[Event(name="Delete",type="smashedapples.air.sqlite.events.SQLiteSaveEvent")]
	
	public class SQLiteSaveCommand extends SQLiteBaseCommand
	{
		public function SQLiteSaveCommand(  db:SQLiteDB, 
											tableName:String, 
											parameters:Object = null, 
											result:Function = null, 
											fault:Function = null )
		{	
			super( db, tableName, parameters, result, fault );
		}
		
		
		
		
		
		
		public function get isInsert():Boolean
		{
			// if the key doesn't exist it's an insert
			if( !parameters.hasOwnProperty( this.pkName ) )
				return true;
			
			// if the key is a not a number it's an insert
			if( isNaN( Number(parameters[this.pkName] ) ) )
				return true;
			
			// if the key exsits and the value == null or -1 it's an insert
			if(  parameters[this.pkName] == null ||
				 parameters[this.pkName] == -1 )
				 return true;
	
			return false;
		}
		
		public function get isUpdate():Boolean
		{
			if(  this.isInsert )
				return false;
			return true;
		}
		
		
		// EVENT HANDLERS
		
		
		public function resultHandler( event:SQLEvent ):void
		{	
			
			// pull out the statement
			var statement:SQLStatement = event.target as SQLStatement;

			var data:Object = this.parameters;
			var inserted:Boolean = false;
			
			if( isInsert )
			{	
				// get the last inserted row and set it to the pk if it's an insert
    			data[this.pkName] = ( statement.getResult() as SQLResult).lastInsertRowID;	
    			inserted = true;
			}
			
			// create response
			var response:SQLiteSaveResponse = new SQLiteSaveResponse( inserted, this.table, data );
						
			// invoke response
			if( this.result != null )
				result( response );
			
			
			db.dispatchEvent( new SQLiteSaveEvent( response ) );
			
		}
		
		public function faultHandler( event:SQLErrorEvent ):void
		{
			this.db.addToDebug( event );
		}
		
		
	}
}